package com.sooth.admin.config;

import com.dream.boot.bean.ConfigurationBean;
import com.dream.mate.logic.inject.LogicInject;
import com.dream.mate.permission.inject.PermissionInject;
import com.dream.mate.tenant.inject.TenantInject;
import com.dream.system.inject.Inject;
import com.dream.template.sequence.Sequence;
import com.sooth.common.core.lang.SnowFlake;
import com.sooth.common.dream.handler.SoothLogicHandler;
import com.sooth.common.dream.handler.SoothPermissionHandler;
import com.sooth.common.dream.handler.SoothTenantHandler;
import com.sooth.common.dream.sequence.SnowFlakeSequence;
import com.sooth.common.plugin.Module;
import com.sooth.common.plugin.ModuleSelector;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

import static com.sooth.micro.camunda.service.ICamundaApiService.CAMUNDA_BPM_DATASOURCE;
import static com.sooth.micro.camunda.service.ICamundaApiService.CAMUNDA_BPM_ENABLED;

@Configuration
public class DreamConfig {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource dataSource() {
        return new HikariDataSource();
    }

    @ConditionalOnProperty(CAMUNDA_BPM_ENABLED)
    @Bean(CAMUNDA_BPM_DATASOURCE)
    @ConfigurationProperties(prefix = "spring.datasource.camunda")
    public DataSource camundaDataSource() {
        return new HikariDataSource();
    }

    @Bean
    public Sequence sequence() {
        return new SnowFlakeSequence(new SnowFlake());
    }

    @Bean
    public ConfigurationBean configurationBean() {
        List<String> tablePackages = new ArrayList<>();
        List<String> mapperPackages = new ArrayList<>();
        List<Module> moduleList = ModuleSelector.MODULE_LIST;
        for (Module module : moduleList) {
            tablePackages.addAll(module.tables());
            mapperPackages.addAll(module.mappers());
        }
        return new ConfigurationBean(tablePackages, mapperPackages);
    }

    @Bean
    public Inject[] injects() {
        return new Inject[]{new PermissionInject(new SoothPermissionHandler()), new LogicInject(new SoothLogicHandler()), new TenantInject(new SoothTenantHandler())};
    }
}
